package com.yanqu.road.web.controller.game;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.dao.db.DBManager;
import com.yanqu.road.dao.db.DatabaseMgr;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.entity.admin.AdminResult;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.config.MallMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.utils.config.Config;
import com.yanqu.road.utils.date.DateHelper;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.*;

/**
 * 50用户订单查询
 */
@RestController
@RequestMapping("/game/admin")
public class AdminOrderController {

    /**
     * 50.1 订单查询
     */
    @ResponseBody
    @RequestMapping(value = "allOrder/search", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String allOrderSearch(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int pageNum = jsonObject.getIntValue("pageNum");
        int pageSize = jsonObject.getIntValue("pageSize");

        long playerId = 0;
        if(jsonObject.containsKey("playerId")){
            playerId = jsonObject.getLongValue("playerId");
        }
        if(playerId <= 0){
            return AdminResult.failMsg("玩家缺失").toJsonString();
        }

        List<Map<String, Object>> matchIdList = searchAllOrder(jsonObject, playerId);

        int startIndex = (pageNum - 1) * pageSize;
        startIndex = Math.max(0, startIndex);

        List<Map<String, Object>> searchList = new ArrayList<>();
        for (int i = startIndex; i < startIndex + pageSize && i < matchIdList.size(); i++) {
            searchList.add(matchIdList.get(i));
        }
        AdminResult result = AdminResult.defaultInstance();
        result.getData().put("total", matchIdList.size());
        result.getData().put("row", searchList);

        return result.toJsonString();
    }

    /**
     * 50.2订单导出
     */
    @ResponseBody
    @RequestMapping(value = "allOrder/export", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String allOrderExport(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        long playerId = 0;
        if(jsonObject.containsKey("playerId")){
            playerId = jsonObject.getLongValue("playerId");
        }
        if(playerId <= 0){
            return AdminResult.failMsg("玩家缺失").toJsonString();
        }

        List<Map<String, Object>> matchIdList = searchAllOrder(jsonObject, playerId);
        StringBuilder builder = new StringBuilder();
        if(!matchIdList.isEmpty()){
            Map<String, Object> objectMap = matchIdList.get(0);
            List<String> list = new ArrayList<>(objectMap.keySet());
            for (int i = 0; i < list.size(); i++) {
                builder.append(list.get(i));
                if(i != list.size() -1){
                    builder.append(",");
                }
                if(i == list.size() - 1){
                    builder.append("\n");
                }
            }
            for (Map<String, Object> map : matchIdList) {
                for (int i = 0; i < list.size(); i++) {
                    builder.append(map.get(list.get(i)));
                    if(i != list.size() -1){
                        builder.append(",");
                    }
                }
                builder.append("\n");
            }
        }
        return builder.toString();
    }

    private List<Map<String, Object>> searchAllOrder(JSONObject jsonObject, long playerId) {
        int isTokens = 0;

        if(jsonObject.containsKey("isTokens")){
            isTokens = jsonObject.getIntValue("isTokens");
        }

        String statusNo = "";
        if(jsonObject.containsKey("statusNo")){
            statusNo = jsonObject.getString(statusNo);
        }
        int status = -1;
        if("PreOrder".equals(statusNo)){
            status = 0;
        }else if("ToBeCharged".equals(statusNo)){
            status = 1;
        }else if("HasBeenCharged".equals(statusNo)){
            status = 2;
        }else if("".equals(statusNo)){

        }

        long beginTime = 0;
        if(jsonObject.containsKey("startTime")){
            beginTime = DateHelper.str2timestamp(jsonObject.getString("startTime"));
        }
        long endTime = 0;
        if(jsonObject.containsKey("endTime")){
            endTime = DateHelper.str2timestamp(jsonObject.getString("endTime"));
        }

        //拼接sql进行查询
        StringBuilder sqlBuilder = new StringBuilder();
        List<DbParameter> parameterList = new ArrayList<>();

        long serverId = 0;
        JSONArray serverIds = jsonObject.getJSONArray("serverIds");
        for (int i = 0; i < serverIds.size(); i++) {
            serverId = serverIds.getLongValue(i);
            break;
        }

        if(isTokens == 0 || isTokens == 1){
            sqlBuilder.append("SELECT urd.userId,urd.createTime,urd.updateTime,urd.amount as price,urd.mallId");
            sqlBuilder.append(",urd.mallName as productName,urd.orderNo,urd.sdkOrderNo,urd.orderStatus,1 as orderType ");
            sqlBuilder.append("from t_u_recharge_detail urd where urd.userId = ? ");
            sqlBuilder.append("union all ");
            sqlBuilder.append("SELECT urd.userId,urd.createTime,urd.updateTime,urd.amount as price,urd.mallId");
            sqlBuilder.append(" ,'' as productName,'' as orderNo, urd.sdkOrderNo,urd.orderStatus,1 as orderType ");
            sqlBuilder.append(" from t_u_thirdparty_recharge urd");
            sqlBuilder.append(" where urd.userId = ? ");
            parameterList.add(new DbParameter(Types.BIGINT, playerId));
            parameterList.add(new DbParameter(Types.BIGINT, playerId));
        }
        if(isTokens == 0){
            sqlBuilder.append(" union all ");
        }
        if(isTokens == 0 || isTokens == 2){
            sqlBuilder.append(" SELECT userId,logTime AS createTime,logTime AS updateTime,moneyPrice as price,mallId,'' AS productName,'' AS orderNo,'' AS sdkOrderNo, ");
            sqlBuilder.append(" 2 AS orderStatus,2 as orderType ");
            if(Config.isDebug()){
                sqlBuilder.append(" FROM db_bussinessroad_log").append(".t_l_gold_token_buy where userId = ?");
            }else {
                sqlBuilder.append(" FROM db_bussinessroad_log_").append(serverId).append(".t_l_gold_token_buy where userId = ?");
            }
            parameterList.add(new DbParameter(Types.BIGINT, playerId));
        }

        DBManager db = DatabaseMgr.getDbManager();
        db.setConnName(DbNameStrategy.getUserDb());
        Map<Integer, DbParameter> params = new HashMap<>();
        for (int i = 0; i < parameterList.size(); i++) {
            params.put(i+1, parameterList.get(i));
        }
        List<Map<String, Object>> mapList = db.executeQuery(sqlBuilder.toString(), params);
        mapList.sort((o1, o2) -> ((Timestamp)o2.get("createTime")).compareTo(((Timestamp)o1.get("createTime"))));

        List<Map<String, Object>> matchIdList = new ArrayList<>();

        for (Map<String, Object> objectMap : mapList) {
            //订单状态
            if(status != -1){
                Object orderStatus = objectMap.get("orderStatus");
                if(!Objects.equals(status, orderStatus)){
                    continue;
                }
            }
            //条件过滤
            //时间条件
            if(beginTime > 0){
                Timestamp createTime = (Timestamp)objectMap.get("createTime");
                if(beginTime > createTime.getTime()){
                    continue;
                }
            }
            if(endTime > 0){
                Timestamp createTime = (Timestamp)objectMap.get("createTime");
                if(endTime < createTime.getTime()){
                    continue;
                }
            }

            Timestamp createTime = (Timestamp)objectMap.get("createTime");
            Timestamp updateTime = (Timestamp)objectMap.get("updateTime");

            objectMap.put("createTime", DateHelper.getCurrentDateTimeString(createTime.getTime()));
            objectMap.put("updateTime", DateHelper.getCurrentDateTimeString(updateTime.getTime()));

            long userId = (long)objectMap.get("userId");
            UserInfo userInfo = UserMgr.getUserInfoInRAM(userId);
            if(userInfo != null){
                objectMap.put("playerId", userId);
                objectMap.put("openId", userInfo.getOpenId());
                objectMap.put("nickName", userInfo.getNickName());
                objectMap.put("registerTime", DateHelper.getCurrentDateTimeString(userInfo.getRegisterTime() * 1000));
                if(Objects.isNull(objectMap.get("productName")) || Objects.equals("", objectMap.get("productName"))){
                    int mallId = (int)objectMap.get("mallId");
                    MallInfo mallInfo = MallMgr.getMallInfoByMallId(mallId);
                    if(mallInfo != null){
                        String mallName = mallInfo.getMallName();
                        String content = MultipleLanguageMgr.getContent(mallName, userInfo.getLanguage());
                        if(Objects.equals(mallName, content)){
                            content = ServerLanguageMgr.getContent(mallName, userInfo.getLanguage());
                        }
                        objectMap.put("productName", content);
                    }
                }
            }
            long orderStatus = (long)objectMap.get("orderStatus");
            if(orderStatus == 0){
                objectMap.put("orderStatus",  "PreOrder");
            }else if(orderStatus == 1){
                objectMap.put("orderStatus",  "ToBeCharged");
            }else if(orderStatus == 2){
                objectMap.put("orderStatus",  "HasBeenCharged");
            }else if("".equals(orderStatus)){

            }
            matchIdList.add(objectMap);
        }
        return matchIdList;
    }
}
